import * as electron from 'electron'
import { currentData } from './currentdata';
import { MapEditor } from './mapeditor';

export function initPreviewBoard() {
    const webview = document.getElementById("runtimeDiv");
    if (webview) {

        const search = location.search;
        const param = new URLSearchParams(search)
        const gameURL = decodeURIComponent(param.get("gameURL") as string);
        webview.setAttribute("src", gameURL + "/index.html")
    }
}

export function reloadPreviewBoard() {
    const runtimeDiv = document.getElementById("runtimeDiv") as electron.WebviewTag;
    if (runtimeDiv) {
        runtimeDiv.reload();
    }
}

let editorMode = ""

export function openMapEditor() {
    if (editorMode == "map") {
        return;
    }
    const data = currentData.getCurrentData();
    const metadata = currentData.getCurrentMetaData();
    editorMode = "map"

    const mapEditorDiv = document.getElementById("mapEditor") as HTMLElement;
    mapEditorDiv.style.display = "block";
    editor = new MapEditor(mapEditorDiv);
    editor.show();
    const previewPanel = document.getElementById("previewPanel") as HTMLElement;
    previewPanel.style.display = "none";
}



export function openPreviewDebugPanel() {
    if (editorMode != "preview") {
        alert('必须在预览模式下才能打开调试面板')
    }
    setTimeout(() => {
        const runtimeDiv = document.getElementById("runtimeDiv") as electron.WebviewTag;
        runtimeDiv.openDevTools();
    }, 500)
}


let editor: MapEditor

export function openPreviewPanel(refresh: boolean) {

    if (editorMode == "preview") {
        return;
    }
    editorMode = "preview"
    const mapEditorDiv = document.getElementById("mapEditor") as HTMLElement;
    mapEditorDiv.style.display = "none";

    if (editor) {
        editor.hide();
    }


    const previewPanel = document.getElementById("previewPanel") as HTMLElement;
    previewPanel.style.display = "block";

    if (refresh) {
        setTimeout(() => {
            reloadPreviewBoard();
        }, 300)
    }


}